package cn.lee.test.controller;

import cn.lee.test.biz.LoginBiz;
import cn.lee.test.common.dataFormat.RequestResult;
import cn.lee.test.model.User;
import cn.lee.test.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : lichl(李承霖)
 * create: 2022/2/23 20:10 周三
 */

@RestController
@RequestMapping("/api")
@Api(tags = {"jwt_demo接口"})
public class TwtTestController{
  
  
  @Autowired
  private HttpServletRequest request;
  
  @Autowired
  private LoginBiz loginBiz;
  
  @Autowired
  private UserService userService;
  
  
  @GetMapping("/login/creatUser")
  @ApiOperation("创建测试用户")
  public RequestResult<User> creatUser(){
    User userData = new User();
    userData.setUserName("lee" + (int) Math.floor(Math.random() * 90 + 10));
    userData.setPassword("12345");
    userData.setAge(18);
    userData.setUserNickName("玉面小霸王" + (int) Math.floor(Math.random() * 90 + 10));
    return new RequestResult<>("200", "success", userService.curd_create(userData));
  }
  
  @SneakyThrows
  @PostMapping("login")
  @ApiOperation("用户登录")
  // 由于是demo所以用明文密码
  public RequestResult<String> userLogin(@RequestParam String username, @RequestParam String password){
    
    // 判断登录
    if(StringUtils.isNotEmpty(loginBiz.login(username, password))){
      return new RequestResult<>("200", "success", loginBiz.login(username, password));
    }else{
      throw new Exception("login fail");
    }
    
  }
  
  
  @GetMapping("getUser")
  @ApiOperation("获取登录用户信息")
  public RequestResult<User> getUser(){
    
    return new RequestResult<>("200", "success", userService.getLoginUser());
  }
  
  @PostMapping("getHttpInfo")
  @ApiOperation("获取Http信息")
  public Map<String, Object> getHttp(){
    Map<String, Object> result = new HashMap<String, Object>();
    result.put("user-agent", getUserAgent());
    result.put("headers", getHeadersInfo());
    return result;
  }
  
  //get user agent
  private String getUserAgent(){
    return request.getHeader("user-agent");
  }
  
  //get request headers
  private Map<String, String> getHeadersInfo(){
    Map<String, String> map = new HashMap<String, String>();
    Enumeration headerNames = request.getHeaderNames();
    while(headerNames.hasMoreElements()){
      String key = (String) headerNames.nextElement();
      String value = request.getHeader(key);
      map.put(key, value);
    }
    return map;
  }
  
}
